package com.smarttest.portal.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.POIXMLException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.smarttest.common.beans.GeneralResult;
import com.smarttest.common.beans.GeneralResultWithStatus;
import com.smarttest.common.util.TestLinkUtil;
import com.smarttest.portal.service.FileService;

import br.eti.kinoshita.testlinkjavaapi.TestLinkAPI;
import br.eti.kinoshita.testlinkjavaapi.model.TestProject;



@Controller
@RequestMapping("/file")
public class FileuploadController {
	@Autowired
	FileService fileService;
	
	
	@RequestMapping(value = "/upload.action",method = RequestMethod.POST)
	@ResponseBody
	public GeneralResult fileUpload(@RequestParam(value = "fileUpload")MultipartFile fileUpload) {
		int result = fileService.uploadFile(fileUpload);
		//为了保证功能的兼容性，需要把Result转换成json格式的字符串。
		if(result==200){
			return GeneralResult.ok(null, "上传成功");
		}else{
			return GeneralResult.error("上传异常");
		}
	}
	
	
	@RequestMapping(value = "/uploadwithuser.action",method = RequestMethod.POST)
	@ResponseBody
	public GeneralResult fileUploadWithUser(HttpServletRequest request,@RequestParam(value = "fileUpload")MultipartFile fileUpload) {
		String userName = request.getRemoteUser();
		int result = fileService.uploadFileWithUser(userName,fileUpload);
		//为了保证功能的兼容性，需要把Result转换成json格式的字符串。
		if(result==200){
			return GeneralResult.ok(null, "上传成功");
		}else{
			return GeneralResult.error("上传异常");
		}
	}
	@RequestMapping(value = "/uploadCasewithuser.action",method = RequestMethod.POST)
	@ResponseBody
	public GeneralResultWithStatus fileUploadCaselWithUser(HttpServletRequest request,@RequestParam(value = "fileUpload")MultipartFile fileUpload) {
		String userName = request.getRemoteUser();
		Object result = fileService.uploadCaseWithUser(userName,fileUpload);
		//为了保证功能的兼容性，需要把Result转换成json格式的字符串。
		if(result instanceof Integer && (int)result ==500){
			return GeneralResultWithStatus.error("上传异常");
		}else{
			return GeneralResultWithStatus.okData(null, result.toString());
		}
	}
	@RequestMapping(value = "/uploadMQwithuser.action",method = RequestMethod.POST)
	@ResponseBody
	public GeneralResultWithStatus fileUploadMQlWithUser(HttpServletRequest request,@RequestParam(value = "fileUpload")MultipartFile fileUpload) {
		String userName = request.getRemoteUser();
		Object result = fileService.uploadMQWithUser(userName,fileUpload);
		//为了保证功能的兼容性，需要把Result转换成json格式的字符串。
		if(result instanceof Integer && (int)result ==500){
			return GeneralResultWithStatus.error("上传异常");
		}else{
			return GeneralResultWithStatus.okData(null, result.toString());
		}
	}
	@RequestMapping(value = "/importCase.action",method = RequestMethod.POST)
	@ResponseBody
	public GeneralResultWithStatus fileUploadImportCase(HttpServletRequest request) {
		String userName = request.getRemoteUser();
		TestLinkAPI api = TestLinkUtil.getApi();		
		int projectid = Integer.parseInt(request.getParameter("projectid"));
		String sheetname = request.getParameter("sheetname");
		String fileName = request.getParameter("fileName");
		int result = fileService.importcase(api,projectid, userName, sheetname, fileName);
		//为了保证功能的兼容性，需要把Result转换成json格式的字符串。
		if(result==200){
			return GeneralResultWithStatus.ok(null, "导入成功");
		}else if (result==201){
			return GeneralResultWithStatus.error("导入失败,当前用户"+userName+"没有该工程的权限");
		}
		else{
			return GeneralResultWithStatus.error("导入失败");
		}
	}
	/**
	 * 获取testlink的所有工程在前端展示
	 */
	@RequestMapping(value = "/getProjects.action",method = RequestMethod.GET)
	@ResponseBody
	public  GeneralResultWithStatus getProjects(HttpServletRequest request) {
		GeneralResultWithStatus result;
		try{
			TestLinkAPI api = TestLinkUtil.getApi();
			TestProject[] tps = api.getProjects();
			String projectsStr = "";
			for (int i = 0;i < tps.length; i++) {
				int id = tps[i].getId();
				String name = tps[i].getName();
				projectsStr += "<option value=\""+id+"\">"+name+"</option>";
			}
			result = GeneralResultWithStatus.okData(null, projectsStr);
		}
		catch (Exception e) {
			result = GeneralResultWithStatus.error("读取testlink工程失败");
		}
		return result;
	}
	/**
	 * 根据excel文件名获取所有sheet并生成html代码给前端展示
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getsheets.action",method = RequestMethod.GET)
	@ResponseBody
	public  GeneralResultWithStatus getSheets(HttpServletRequest request) {
		GeneralResultWithStatus result;
		try{
			String filename = request.getParameter("filename").trim();
			 XSSFWorkbook xswb = null;
		        //出现异常时，创建2003版本的Excel文件对象
		        HSSFWorkbook hswb = null;
				String sheetsStr = "";
		        try {  
		            xswb = new XSSFWorkbook(new FileInputStream(new File(filename)));
		            // 创建对工作表的引用
		            for (int i = 0; i < xswb.getNumberOfSheets();i++) {
		            	sheetsStr += "<option value=\""+xswb.getSheetName(i)+"\">"+xswb.getSheetName(i)+"</option>";
		            } 
		        }
		        catch (FileNotFoundException e) {  
		        	e.printStackTrace(); 
		        } catch (POIXMLException e) {  
					try {
						hswb = new HSSFWorkbook(new FileInputStream(new File(filename)));
						for (int i = 0; i < hswb.getNumberOfSheets();i++) {
			            	sheetsStr += "<option value=\""+i+"\">"+hswb.getSheetName(i)+"</option>";
						}  
					}
					catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} 
					catch (NullPointerException e1) {
						// TODO Auto-generated catch block
						System.out.println("In 2003 excel,TestCase and TestCase between can't have empty row.");
						System.out.println("OR some columns or some rows are not in border.");
						e1.printStackTrace();
					} 
					catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		        }
		        catch (IOException e) {  
		        	e.printStackTrace();   
		        } catch (NullPointerException e1) {
					// TODO Auto-generated catch block
					System.out.println("In 2007 excel,TestCase and TestCase between can't have empty row.");
					System.out.println("OR some columns or some rows are not in border.");
					e1.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			result = GeneralResultWithStatus.okData(null, sheetsStr);
		}
		catch (Exception e) {
			result = GeneralResultWithStatus.error("读取testlink工程失败");
		}
		return result;
	}
}
